package com.sunyur.tailor.channel.service.inner.currency.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.sunyur.tailor.channel.common.inner.base.SunyurResult;
import com.sunyur.tailor.channel.common.inner.util.SunyurClientUtil;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.service.inner.currency.param.BatchSyncCurrencyParam;
import com.sunyur.tailor.channel.service.inner.currency.service.SunyurCurrencyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service("SunyurCurrencyService")
public class SunyurCurrencyServiceImpl implements SunyurCurrencyService {

    private static final Logger LOGGER_INFO = LoggerFactory.getLogger(SunyurCurrencyServiceImpl.class);
    private static final Logger LOGGER_ERROR = LoggerFactory.getLogger(SunyurCurrencyServiceImpl.class);

    /**
     * 请求商越Client
     */
    @Autowired
    private SunyurClientUtil sunyurClient;

    /**
     * 汇率同步 链接
     */
    @Value("${sunyur.api.batchSyncCurrency}")
    private String batchSyncCurrency;

    @Override
    public ChannelResult<Boolean> batchSyncCurrency(List<BatchSyncCurrencyParam> batchSyncCurrencyParam) throws Exception {
        LOGGER_INFO.info("SunyurCurrencyServiceImpl batchSyncCurrency batchSyncCurrencyParam.size is {}， param is {}", batchSyncCurrencyParam.size(), JSON.toJSONString(batchSyncCurrencyParam));
        if (CollectionUtils.isEmpty(batchSyncCurrencyParam)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurCurrencyServiceImpl batchSyncCurrency batchSyncCurrencyParam is null");
        }
        // 参数按长度分割
        List<List<BatchSyncCurrencyParam>> currencyList = Lists.partition(batchSyncCurrencyParam, 20);
        // 返回错误信息结果集
        List<String> errorMsgList = Lists.newArrayList();
        // 循环调用创建或更新供应商接口
        for (int i = 0; i < currencyList.size(); i++) {
            // 调用主线创建或更新供应商接口
            SunyurResult sunyurResult = sunyurClient.execPost(batchSyncCurrency, JSON.toJSONString(currencyList.get(i)), null);
            // 某次调用主线返回错误（本次新增失败，记录错误信息，继续新增下一批）
            if (!"success".equals(sunyurResult.getCode())) {
                LOGGER_ERROR.error("第{}批失败， SunyurCurrencyServiceImpl batchSyncCurrency loop call sunyur request fail, param is {}, result is {}", i + 1, JSON.toJSONString(currencyList.get(i)), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add("第" + i + "批失败，" + sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(Boolean.TRUE);
    }
}
